package com.example.todo;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {
	
	DBAdapter myDb; //Instantiate the db
	
	public final static String EXTRA_TASK_NAME = "com.example.ToDo.MESSAGE";
	public final static String EXTRA_CATEGORY = "com.example.ToDo.CATEGORY";
	public final static String EXTRA_SUBJECT = "com.example.ToDo.SUBJECT";
	public final static String EXTRA_PROJECT = "com.example.ToDo.PROJECT";
	public final static String EXTRA_DATE = "com.example.ToDo.DATE";
	public final static String EXTRA_LOCATION = "com.example.ToDo.LOCATION";
	public final static String EXTRA_DESCRIPTION = "com.example.ToDo.DESCRIPTION";
	public final static String EXTRA_ID = "com.example.ToDo.ID";
	public final static int TEST_ID = 0;
	public static String EXTRA_FILTER_CATEGORY;
	
    private NavigationDrawerFragment mNavigationDrawerFragment;
    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Don't allow the keyboard to pup up when the page loads.
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
               
        mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
        // Show the database on startup:
        openDB();
    }       
    
// THIS IS THE START TO THE NAVIGATION MENU////////////////////////////////////////////////////////////
	@Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        android.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
    }
    public void onSectionAttached(int number) {
        switch (number) {
            case 1:           
            	mTitle = getString(R.string.app_name);
                break;
             case 2:
                Intent intentFilter = new Intent(this, FilterActivity.class);
               	startActivity(intentFilter);
            	mTitle = getString(R.string.title_activity_filter);
                break;
             case 3:
                Intent intentHome = new Intent(this, FilteredResultsActivity.class);
                String category = "Home";
                intentHome.putExtra(EXTRA_FILTER_CATEGORY,  category);
            	startActivity(intentHome);
            	mTitle = getString(R.string.task_category);
            	break;
             case 4:
                 Intent intentWork = new Intent(this, FilteredResultsActivity.class);
                 String work_category = "Work";
                 intentWork.putExtra(EXTRA_FILTER_CATEGORY,  work_category);
             	 startActivity(intentWork);
             	 mTitle = getString(R.string.task_category_Work);
             	break;
		    case 5:
		    	Intent intentSchool = new Intent(this, FilteredResultsActivity.class);
		    	String school_category = "School";
		    	intentSchool.putExtra(EXTRA_FILTER_CATEGORY,  school_category);
		    	startActivity(intentSchool);
		    	mTitle = getString(R.string.task_category_School);
		    	break;
		    case 6:
		    	Intent intentFamily = new Intent(this, FilteredResultsActivity.class);
		    	String family_category = "Family";
		    	intentFamily.putExtra(EXTRA_FILTER_CATEGORY,  family_category);
		    	startActivity(intentFamily);
		    	mTitle = getString(R.string.task_category_School);
		    	break;
		    default:
		    	Intent intent = new Intent(this, MainActivity.class);
            	startActivity(intent);
        }
    }
    public void restoreActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
        	MenuInflater inflater = getMenuInflater();
        	inflater.inflate(R.menu.main, menu);
            //getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    // A placeholder fragment containing a simple view. 
    public static class PlaceholderFragment extends Fragment {
        //The fragment argument representing the section number for this fragment.
        private static final String ARG_SECTION_NUMBER = "section_number";
        //Returns a new instance of this fragment for the given section number.    
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }
        public PlaceholderFragment() {
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            // THE FOLLOWING PUTS THE NUMBER OF LEVEL IS CURRENTLY ON TOP (VERY ANNOYING)
            //TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            //textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
           // THIS RELATES TO THE NAV SIDE MENU
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));            
        }        
    }
// END OF NAVIGATION MENU CODE ////////////////////////////////////////////////////////
    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		closeDB();
	}
	private void openDB() {
		myDb = new DBAdapter(this);
		myDb.open();
	}
	private void closeDB() {
		myDb.close();
	}
    public void newTask(View view){
	//Do something
    	Intent intent = new Intent(this, CreateNewTaskActivity.class);
    	EditText editText = (EditText) findViewById(R.id.new_task_text);
    	String message = editText.getText().toString();
    	intent.putExtra(EXTRA_TASK_NAME,  message);
    	startActivity(intent);
    }
    
    // Display the entire table
    public void onClick_test_db(View view){
    	myDb.open();
    	showDatabase();
    }
    
    //Show the database
    private void showDatabase(){
    	Cursor cursor = myDb.getAllRows();
        displayRecordSet(cursor);
    }
    
    //Display an entire record set to the screen
    @SuppressLint("ResourceAsColor")
	private void displayRecordSet(Cursor cursor) {
		String message = "";
		LinearLayout buttonContainer = (LinearLayout) findViewById(R.id.button_layout);
	    buttonContainer.removeAllViews();
		
		//Reset cursor to start, checking to see if there's data:
		if (cursor.moveToFirst()){
			do{
				//Process data:
				final int id = cursor.getInt(DBAdapter.COL_ROWID);
				final String task_id = Integer.toString(id);
				final String  task_name = cursor.getString(DBAdapter.COL_TASK_NAME);
				final String category = cursor.getString(DBAdapter.COL_CATEGORY);
				final String subject = cursor.getString(DBAdapter.COL_SUBJECT);
				final String project = cursor.getString(DBAdapter.COL_PROJECT);
				final String date = cursor.getString(DBAdapter.COL_DATE);
				final String description = cursor.getString(DBAdapter.COL_DESCRIPTION);
				final String location = cursor.getString(DBAdapter.COL_LOCATION);
							
			// Display all of the tasks as buttons
			Button button = new Button(this);
			button.setText(task_name);
			// Allow the buttons to listen for it to be clicked.
			button.setOnClickListener(new View.OnClickListener() {
			    @Override
			    public void onClick(View v) {
			    	Intent intent = new Intent(MainActivity.this, TaskDetailsActivity.class);;
			    	intent.putExtra(EXTRA_ID,  task_id);
			    	intent.putExtra(EXTRA_TASK_NAME,  task_name);
			    	intent.putExtra(EXTRA_CATEGORY,  category);
			    	intent.putExtra(EXTRA_SUBJECT,  subject);
			    	intent.putExtra(EXTRA_PROJECT,  project);
			    	intent.putExtra(EXTRA_DATE,  date);
			    	intent.putExtra(EXTRA_LOCATION,  location);
			    	intent.putExtra(EXTRA_DESCRIPTION,  description);
			    	startActivity(intent);
			    }
			});				
			LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);			
			buttonContainer.addView(button, lp);
			} while(cursor.moveToNext());
		}
		//Close cursor to avoid resource leak.
		cursor.close();
	}
    public void onClick_task_details(View view){
    	Intent intent = new Intent(this, TaskDetailsActivity.class);
    	startActivity(intent);
    }
    
    // Clear out the entire database (This button is hidden and is used for testing only)
    public void onClick_ClearAll(View view){
    	myDb.deleteAll();
    	//Clear out the buttons
    	LinearLayout buttonContainer = (LinearLayout) findViewById(R.id.button_layout);
    	buttonContainer.removeAllViews(); 	
    }
    
    //Sort the buttons by name
    public void onClick_SortName(View view){
    	myDb.open();
    	String colm = "name";
		Cursor c = myDb.sort(colm);
        displayRecordSet(c);
        myDb.close();
		c.close();
    }
}
